package xyz.labmem.lipx.core.codec

import cn.hutool.core.util.ZipUtil
import cn.hutool.crypto.SecureUtil
import com.alibaba.fastjson2.JSON
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
import xyz.labmem.lipx.core.context.Secret
import xyz.labmem.lipx.core.protocol.LabMessage
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream

/**
 * @description: do something
 * @author: ltty
 * @date: 2022/5/30 15:13
 */
class LabMessageEncoder : MessageToByteEncoder<LabMessage>() {
    override fun encode(ctx: ChannelHandlerContext, msg: LabMessage, out: ByteBuf) {

        val byteArrayOutputStream = ByteArrayOutputStream()
        DataOutputStream(byteArrayOutputStream).use { dataOutputStream ->
            val labMessageType = msg.type!!
            dataOutputStream.writeInt(labMessageType.code)
            //加密
            val secretData = SecureUtil.aes(Secret.getKey()).encrypt(JSON.toJSONString(msg.metaData))
            dataOutputStream.writeInt(secretData.size)
            dataOutputStream.write(secretData)
            if (msg.data != null && msg.data!!.isNotEmpty()) {
                dataOutputStream.write(msg.data!!)
            }
            val data = byteArrayOutputStream.toByteArray()
            //压缩
            val gzip = ZipUtil.gzip(data)
            out.writeInt(gzip.size)
            out.writeBytes(gzip)
            dataOutputStream.close()
            byteArrayOutputStream.close()
        }
    }
}